<template>
  <div id="mapView" class="map-view">
    <!-- 图层说明提示 -->
    <div class="layer-info-tip">
      <div class="tip-title">图层说明</div>
      <div class="tip-content">
        <div class="tip-item">
          <span class="color-box highway-good"></span> 高速公路 - 良好
        </div>
        <div class="tip-item">
          <span class="color-box highway-normal"></span> 高速公路 - 一般
        </div>
        <div class="tip-item">
          <span class="color-box highway-bad"></span> 高速公路 - 较差
        </div>
        <div class="tip-item">
          <span class="color-box highway-repair"></span> 高速公路 - 维修中
        </div>
        <div class="tip-item">
          <span class="color-box entrance"></span> 进出口
        </div>
        <div class="tip-item">
          <span class="color-box service"></span> 服务区
        </div>
      </div>
    </div>

    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <div class="card-header">
          <el-icon><Menu /></el-icon>
          <span>控制面板</span>
        </div>
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <template #title>
              <div class="collapse-title">
                <span>图层显示控制</span>
              </div>
            </template>
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox
                v-model="layerVisibility.entrance"
                @change="toggleLayerVisibility('entrance')"
              >
                <el-icon><TurnOff /></el-icon> 进出口
              </el-checkbox>
              <el-checkbox
                v-model="layerVisibility.service"
                @change="toggleLayerVisibility('service')"
              >
                <el-icon><Shop /></el-icon> 服务区
              </el-checkbox>
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="设施查询" name="query">
            <template #title>
              <div class="collapse-title">
                <el-icon><Search /></el-icon>
                <span>设施查询</span>
              </div>
            </template>
            <el-space direction="vertical" alignment="stretch" size="small">
              <div class="query-section">
                <div class="section-title">服务区管理</div>
                <el-select
                  v-model="selectedServiceId"
                  filterable
                  placeholder="请选择服务区"
                  style="width: 100%"
                  @change="handleServiceSelected"
                >
                  <el-option
                    v-for="service in serviceList"
                    :key="service.attributes.OBJECTID"
                    :label="service.attributes.service_name"
                    :value="service.attributes.OBJECTID"
                  ></el-option>
                </el-select>
                <div class="note-text">注：双击地图上的服务区可查询和修改</div>
              </div>

              <div class="query-section">
                <div class="section-title">进出口管理</div>
                <el-select
                  v-model="selectedEntranceId"
                  filterable
                  placeholder="请选择进出口"
                  style="width: 100%"
                  @change="handleEntranceSelected"
                >
                  <el-option
                    v-for="entrance in entranceList"
                    :key="entrance.attributes.OBJECTID"
                    :label="entrance.attributes.entrance_name"
                    :value="entrance.attributes.OBJECTID"
                  ></el-option>
                </el-select>
                <div class="note-text">注：双击地图上的进出口可查询和修改</div>
              </div>
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="导航操作" name="navigation">
            <template #title>
              <div class="collapse-title">
                <el-icon><Guide /></el-icon>
                <span>导航操作</span>
              </div>
            </template>
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startDrawOrigin" :disabled="isDrawing">
                <el-icon><Location /></el-icon> 绘制起点
              </el-button>
              <el-button type="success" @click="findNearestFacility" :disabled="!originPoint">
                <el-icon><Position /></el-icon> 查找最近设施
              </el-button>
              <el-button type="danger" @click="clearRoute" :disabled="!hasRoute">
                <el-icon><Delete /></el-icon> 清除路线
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 导航信息面板 -->
    <div v-if="routeInfo" class="route-info-panel">
      <el-card class="route-card">
        <template #header>
          <div class="route-header">
            <div class="route-title">
              <el-icon><InfoFilled /></el-icon>
              <span>导航信息</span>
            </div>
            <el-button type="text" @click="routeInfo = null">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </template>
        <div class="route-details">
          <div class="route-item">
            <el-icon><LocationInformation /></el-icon>
            <strong>起点:</strong> {{ originPointDesc }}
          </div>
          <div class="route-item">
            <el-icon><Aim /></el-icon>
            <strong>终点:</strong> {{ destinationDesc }}
          </div>
          <div class="route-item">
            <el-icon><Odometer /></el-icon>
            <strong>距离:</strong> {{ routeInfo.distance }}米
          </div>
          <div class="route-item">
            <el-icon><Timer /></el-icon>
            <strong>预计时间:</strong> {{ Math.round(routeInfo.duration / 60) }}分钟
          </div>
          <div class="route-steps">
            <div class="steps-header">
              <el-icon><List /></el-icon>
              <strong>导航步骤:</strong>
            </div>
            <ol class="steps-list">
              <li v-for="(step, index) in routeInfo.steps" :key="index">
                {{ step.instruction }}
              </li>
            </ol>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 设施选择对话框 -->
    <el-dialog v-model="facilitySelectVisible" title="选择目的地" width="500px">
      <div v-if="nearbyFacilities.length > 0">
        <el-radio-group v-model="selectedFacilityId">
          <div v-for="facility in nearbyFacilities" :key="facility.id" class="facility-item">
            <el-radio :label="facility.id">
              {{ facility.name }} ({{ facility.type }}) - 距离: {{ facility.distance }}米
            </el-radio>
          </div>
        </el-radio-group>
      </div>
      <div v-else>
        <p>附近没有找到服务区或进出口</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="facilitySelectVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="navigateToSelectedFacility"
            :disabled="!selectedFacilityId"
          >
            导航
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设施详情对话框 -->
    <el-dialog
      v-model="facilityInfoVisible"
      :title="selectedFacility?.type === 'entrance' ? '进出口信息' : '服务区信息'"
      width="500px"
    >
      <div v-if="selectedFacility">
        <el-descriptions :column="1" border>
          <template v-if="selectedFacility.type === 'entrance'">
            <el-descriptions-item label="进出口编号">{{
              selectedFacility.attributes.entrance_id
            }}</el-descriptions-item>
            <el-descriptions-item label="进出口名称">{{
              selectedFacility.attributes.entrance_name
            }}</el-descriptions-item>
            <el-descriptions-item label="进出口类型">{{
              selectedFacility.attributes.entrance_type
            }}</el-descriptions-item>
            <el-descriptions-item label="所属高速公路">{{
              getHighwayNameByCode(selectedFacility.attributes.highway_code)
            }}</el-descriptions-item>
            <el-descriptions-item label="收费站状态">{{
              selectedFacility.attributes.status
            }}</el-descriptions-item>
          </template>
          <template v-else>
            <el-descriptions-item label="服务区编号">{{
              selectedFacility.attributes.service_id
            }}</el-descriptions-item>
            <el-descriptions-item label="服务区名称">{{
              selectedFacility.attributes.service_name
            }}</el-descriptions-item>
            <el-descriptions-item label="所属高速公路">{{
              getHighwayNameByCode(selectedFacility.attributes.highway_code)
            }}</el-descriptions-item>
            <el-descriptions-item label="服务区等级">{{
              selectedFacility.attributes.service_level
            }}</el-descriptions-item>
            <el-descriptions-item label="服务区状态">{{
              selectedFacility.attributes.status
            }}</el-descriptions-item>
          </template>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="facilityInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="navigateFromFacility"> 从此处导航 </el-button>
          <el-button type="success" @click="navigateToFacility"> 导航到此处 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import SimpleFillSymbol from '@arcgis/core/symbols/SimpleFillSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import Point from '@arcgis/core/geometry/Point.js'
import Polyline from '@arcgis/core/geometry/Polyline.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import { getGaoDeRoute, type Step } from '../utils/gaodeAPI'
import Legend from '@arcgis/core/widgets/Legend.js'
import {
  Location,
  Position,
  Delete,
  Close,
  Menu,
  TurnOff,
  Shop,
  Guide,
  InfoFilled,
  LocationInformation,
  Aim,
  Odometer,
  Timer,
  List,
  Search
} from '@element-plus/icons-vue'

interface FacilityItem {
  id: string
  name: string
  type: 'entrance' | 'service'
  distance: number
  geometry: any
  attributes: any
}

interface RouteInfo {
  distance: number
  duration: number
  steps: Step[]
}

let view: MapView | null = null
let entranceLayer: FeatureLayer | null = null
let serviceLayer: FeatureLayer | null = null
let highwayLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let routeLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let originGraphic: Graphic | null = null
let destinationGraphic: Graphic | null = null
let routeGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  entrance: true,
  service: true,
})

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'query', 'navigation'])

// 导航相关状态
const isDrawing = ref(false)
let originPoint: Point | null = null
const originPointDesc = ref('')
const destinationDesc = ref('')
const hasRoute = ref(false)
const routeInfo = ref<RouteInfo | null>(null)

// 设施选择相关
const facilitySelectVisible = ref(false)
let nearbyFacilities: FacilityItem[] = []
const selectedFacilityId = ref('')

// 设施详情相关
const facilityInfoVisible = ref(false)
let selectedFacility: any = null

// 高速公路列表
let highwayList: Graphic[] = []

// 服务区和进出口列表
let serviceList: Graphic[] = []
let entranceList: Graphic[] = []
const selectedServiceId = ref('')
const selectedEntranceId = ref('')

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  if (layerType === 'entrance' && entranceLayer) {
    entranceLayer.visible = Boolean(layerVisibility.value.entrance)
  } else if (layerType === 'service' && serviceLayer) {
    serviceLayer.visible = Boolean(layerVisibility.value.service)
  }
}

// 开始绘制起点
const startDrawOrigin = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击绘制导航起点')

  // 清除之前的起点
  if (originGraphic && sketchLayer) {
    sketchLayer.remove(originGraphic)
    originGraphic = null
    originPoint = null
  }

  // 开始绘制点
  sketchViewModel.create('point')
}

// 查找最近的设施
const findNearestFacility = async () => {
  if (!originPoint || !entranceLayer || !serviceLayer) return

  try {
    // 创建查询对象
    const query = new Query()
    query.geometry = originPoint
    query.distance = 50000 // 50公里范围内
    query.units = 'meters'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    // 查询进出口
    const entranceResults = await entranceLayer.queryFeatures(query)
    // 查询服务区
    const serviceResults = await serviceLayer.queryFeatures(query)

    // 合并结果并计算距离
    nearbyFacilities = []

    entranceResults.features.forEach((feature) => {
      const point = feature.geometry as Point
      const distance = calculateDistance(originPoint!, point)

      nearbyFacilities.push({
        id: `entrance_${feature.attributes.OBJECTID}`,
        name: feature.attributes.entrance_name,
        type: 'entrance',
        distance: Math.round(distance),
        geometry: feature.geometry,
        attributes: feature.attributes,
      })
    })

    serviceResults.features.forEach((feature) => {
      // 服务区现在是点要素，直接计算距离
      const point = feature.geometry as Point
      const distance = calculateDistance(originPoint!, point)

      nearbyFacilities.push({
        id: `service_${feature.attributes.OBJECTID}`,
        name: feature.attributes.service_name,
        type: 'service',
        distance: Math.round(distance),
        geometry: feature.geometry,
        attributes: feature.attributes,
      })
    })

    // 按距离排序
    nearbyFacilities.sort((a, b) => a.distance - b.distance)

    // 限制显示最近的10个
    nearbyFacilities = nearbyFacilities.slice(0, 10)

    if (nearbyFacilities.length > 0) {
      selectedFacilityId.value = nearbyFacilities[0].id
      facilitySelectVisible.value = true
    } else {
      ElMessage.warning('附近50公里内没有找到服务区或进出口')
    }
  } catch (error) {
    console.error('查询附近设施出错:', error)
    ElMessage.error('查询附近设施失败')
  }
}

// 导航到选中的设施
const navigateToSelectedFacility = () => {
  const facility = nearbyFacilities.find((f) => f.id === selectedFacilityId.value)
  if (!facility) return

  facilitySelectVisible.value = false

  // 设置目的地并计算路线
  setDestination(facility)
  calculateRoute()
}

// 从设施导航
const navigateFromFacility = () => {
  if (!selectedFacility) return

  facilityInfoVisible.value = false

  // 清除之前的路线
  clearRoute()

  // 设置起点为当前设施
  let facilityPoint: Point

  if (selectedFacility.type === 'entrance') {
    facilityPoint = selectedFacility.geometry as Point
    originPointDesc.value = selectedFacility.attributes.entrance_name
  } else {
    // 服务区现在是点要素，直接使用
    facilityPoint = selectedFacility.geometry as Point
    originPointDesc.value = selectedFacility.attributes.service_name
  }

  // 创建起点图形
  if (sketchLayer) {
    originGraphic = new Graphic({
      geometry: facilityPoint,
      symbol: new SimpleMarkerSymbol({
        style: 'circle',
        color: [0, 255, 0, 0.5],
        size: 12,
        outline: {
          color: [0, 255, 0],
          width: 1,
        },
      }),
    })
    sketchLayer.add(originGraphic)
    originPoint = facilityPoint
  }

  // 提示用户选择目的地
  ElMessage.info('请点击地图上的另一个设施作为目的地')
}

// 导航到设施
const navigateToFacility = () => {
  if (!selectedFacility) return

  facilityInfoVisible.value = false

  // 如果没有起点，提示用户先绘制起点
  if (!originPoint) {
    ElMessage.warning('请先绘制起点')
    startDrawOrigin()
    return
  }

  // 设置目的地为当前设施
  setDestination({
    id:
      selectedFacility.type === 'entrance'
        ? `entrance_${selectedFacility.attributes.OBJECTID}`
        : `service_${selectedFacility.attributes.OBJECTID}`,
    name:
      selectedFacility.type === 'entrance'
        ? selectedFacility.attributes.entrance_name
        : selectedFacility.attributes.service_name,
    type: selectedFacility.type,
    distance: 0,
    geometry: selectedFacility.geometry,
    attributes: selectedFacility.attributes,
  })

  // 计算路线
  calculateRoute()
}

// 设置目的地
const setDestination = (facility: FacilityItem) => {
  if (!sketchLayer) return

  // 清除之前的目的地
  if (destinationGraphic) {
    sketchLayer.remove(destinationGraphic)
  }

  // 创建目的地图形
  let destinationPoint: Point

  if (facility.type === 'entrance') {
    destinationPoint = facility.geometry as Point
    destinationDesc.value = facility.name
  } else {
    // 服务区现在是点要素，直接使用
    destinationPoint = facility.geometry as Point
    destinationDesc.value = facility.name
  }

  destinationGraphic = new Graphic({
    geometry: destinationPoint,
    symbol: new SimpleMarkerSymbol({
      style: 'circle',
      color: [255, 0, 0, 0.5],
      size: 12,
      outline: {
        color: [255, 0, 0],
        width: 1,
      },
    }),
  })

  sketchLayer.add(destinationGraphic)
}

// 计算路线
const calculateRoute = async () => {
  if (!originPoint || !destinationGraphic || !routeLayer) return

  try {
    // 获取起点和终点坐标
    const startCoord = `${originPoint.longitude},${originPoint.latitude}`
    const destPoint = destinationGraphic.geometry as Point
    const endCoord = `${destPoint.longitude},${destPoint.latitude}`

    // 调用高德API获取路线
    const routeResponse = await getGaoDeRoute(startCoord, endCoord)

    if (routeResponse.status === '1' && routeResponse.route.paths.length > 0) {
      const path = routeResponse.route.paths[0]

      // 解析路线坐标
      const routeCoordinates: number[][] = []

      path.steps.forEach((step) => {
        // 解析polyline字符串
        const points = step.polyline.split(';')
        points.forEach((point) => {
          const [lng, lat] = point.split(',')
          routeCoordinates.push([parseFloat(lng), parseFloat(lat)])
        })
      })

      // 创建路线图形
      const polyline = new Polyline({
        paths: [routeCoordinates],
        spatialReference: { wkid: 4326 },
      })

      routeGraphic = new Graphic({
        geometry: polyline,
        symbol: new SimpleLineSymbol({
          color: [0, 0, 255, 0.8],
          width: 5,
        }),
      })

      routeLayer.add(routeGraphic)

      // 保存路线信息
      routeInfo.value = {
        distance: parseInt(path.distance),
        duration: parseInt(path.duration),
        steps: path.steps,
      }

      hasRoute.value = true

      // 缩放到路线范围
      view?.goTo(polyline.extent?.expand(1.5))
    } else {
      ElMessage.error('无法计算路线，请尝试其他位置')
    }
  } catch (error) {
    console.error('计算路线出错:', error)
    ElMessage.error('计算路线失败')
  }
}

// 清除路线
const clearRoute = () => {
  if (routeLayer) {
    routeLayer.removeAll()
    routeGraphic = null
  }

  routeInfo.value = null
  hasRoute.value = false
}

// 计算两点之间的距离（米）
const calculateDistance = (point1: Point, point2: Point): number => {
  const R = 6371000 // 地球半径（米）
  const lat1 = ((point1.latitude || 0) * Math.PI) / 180
  const lat2 = ((point2.latitude || 0) * Math.PI) / 180
  const dLat = (((point2.latitude || 0) - (point1.latitude || 0)) * Math.PI) / 180
  const dLon = (((point2.longitude || 0) - (point1.longitude || 0)) * Math.PI) / 180

  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  return R * c
}

// 根据高速公路编码获取名称
const getHighwayNameByCode = (code: string): string => {
  const highway = highwayList.find((h) => h.attributes.highway_code === code)
  return highway ? highway.attributes.highway_name : '未知'
}

// 加载高速公路列表
const loadHighwayList = async () => {
  if (!highwayLayer) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = false

    const result = await highwayLayer.queryFeatures(query)
    highwayList = result.features
  } catch (error) {
    console.error('加载高速公路列表出错:', error)
    ElMessage.error('加载高速公路列表失败')
  }
}

// 加载服务区列表
const loadServiceList = async () => {
  if (!serviceLayer) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = true

    const result = await serviceLayer.queryFeatures(query)
    serviceList = result.features
  } catch (error) {
    console.error('加载服务区列表出错:', error)
    ElMessage.error('加载服务区列表失败')
  }
}

// 加载进出口列表
const loadEntranceList = async () => {
  if (!entranceLayer) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = true

    const result = await entranceLayer.queryFeatures(query)
    entranceList = result.features
  } catch (error) {
    console.error('加载进出口列表出错:', error)
    ElMessage.error('加载进出口列表失败')
  }
}

// 处理服务区选择
const handleServiceSelected = () => {
  if (!selectedServiceId.value) return

  const selectedService = serviceList.find(s => s.attributes.OBJECTID === selectedServiceId.value)
  if (selectedService) {
    // 将地图中心移动到所选服务区
    if (view && selectedService.geometry) {
      view.goTo({
        target: selectedService.geometry,
        zoom: 14
      })

      // 显示服务区信息
      selectedFacility = {
        type: 'service',
        geometry: selectedService.geometry,
        attributes: selectedService.attributes
      }
      facilityInfoVisible.value = true
    }
  }
}

// 处理进出口选择
const handleEntranceSelected = () => {
  if (!selectedEntranceId.value) return

  const selectedEntrance = entranceList.find(e => e.attributes.OBJECTID === selectedEntranceId.value)
  if (selectedEntrance) {
    // 将地图中心移动到所选进出口
    if (view && selectedEntrance.geometry) {
      view.goTo({
        target: selectedEntrance.geometry,
        zoom: 14
      })

      // 显示进出口信息
      selectedFacility = {
        type: 'entrance',
        geometry: selectedEntrance.geometry,
        attributes: selectedEntrance.attributes
      }
      facilityInfoVisible.value = true
    }
  }
}

// 初始化地图
const initMap = () => {
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    center: [116.397428, 39.90923], // 默认中心点（北京）
    zoom: 8,
  })

  // 创建图形图层用于绘制
  sketchLayer = new GraphicsLayer()
  map.add(sketchLayer)

  // 创建路线图层
  routeLayer = new GraphicsLayer()
  map.add(routeLayer)

  // 创建高速公路图层
  highwayLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: true,
    popupTemplate: {
      title: '{highway_name}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'highway_code', label: '高速公路编号' },
            { fieldName: 'highway_level', label: '高速公路等级' },
            { fieldName: 'lanes', label: '车道数' },
            { fieldName: 'status', label: '路况状态' },
            { fieldName: 'speed_limit', label: '限速(km/h)' }
          ]
        }
      ]
    }
  })
  map.add(highwayLayer)

  // 创建进出口图层
  entranceLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayService/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: true,
    popupTemplate: {
      title: '{entrance_name}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'entrance_id', label: '进出口编号' },
            { fieldName: 'entrance_type', label: '进出口类型' },
            { fieldName: 'highway_code', label: '所属高速公路' },
            { fieldName: 'status', label: '收费站状态' },
            { fieldName: 'location_desc', label: '位置描述' }
          ]
        }
      ]
    },
    // 设置进出口图层的样式
    renderer: {
      type: 'simple',
      symbol: new SimpleMarkerSymbol({
        style: 'square',  // 使用方形标记
        color: '#3498DB',  // 蓝色
        size: 10,
        outline: {
          color: '#2980B9',
          width: 1
        }
      }),
      label: '高速公路进出口'
    }
  })
  map.add(entranceLayer)

  // 创建服务区图层 - 使用点要素图层
  serviceLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayServiceLayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: true,
    popupTemplate: {
      title: '{service_name}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'service_id', label: '服务区编号' },
            { fieldName: 'highway_code', label: '所属高速公路' },
            { fieldName: 'service_level', label: '服务区等级' },
            { fieldName: 'status', label: '服务区状态' },
            { fieldName: 'facilities', label: '设施描述' }
          ]
        }
      ]
    },
    // 设置服务区图层的样式
    renderer: {
      type: 'simple',
      symbol: new SimpleMarkerSymbol({
        style: 'diamond',  // 使用菱形标记
        color: '#27AE60',  // 绿色
        size: 12,
        outline: {
          color: '#1E8449',
          width: 1
        }
      }),
      label: '高速公路服务区'
    }
  })
  map.add(serviceLayer)

  // 添加图例
  const legend = new Legend({
    view: view,
    layerInfos: [
      {
        layer: highwayLayer,
        title: '高速公路'
      },
      {
        layer: entranceLayer,
        title: '进出口'
      },
      {
        layer: serviceLayer,
        title: '服务区'
      }
    ]
  })

  // 将图例添加到右下角
  view.ui.add(legend, 'bottom-right')

  // 创建绘图工具
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
    pointSymbol: new SimpleMarkerSymbol({
      style: 'circle',
      color: [0, 255, 0, 0.5],
      size: 12,
      outline: {
        color: [0, 255, 0],
        width: 1,
      },
    }),
  })

  // 监听绘图完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      originGraphic = event.graphic
      originPoint = originGraphic.geometry as Point
      originPointDesc.value = `坐标(${originPoint.longitude?.toFixed(4)}, ${originPoint.latitude?.toFixed(4)})`
      isDrawing.value = false
      ElMessage.success('起点已设置')
    }
  })

  // 监听点击事件，用于选择要素
  view.on('click', async (event) => {
    // 如果正在绘制，不处理点击事件
    if (isDrawing.value) return

    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 100 // 点击容差(米)
    query.units = 'meters'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询进出口图层
      if (entranceLayer && entranceLayer.visible) {
        const entranceResult = await entranceLayer.queryFeatures(query)
        if (entranceResult.features.length > 0) {
          // 找到进出口，显示信息
          selectedFacility = {
            type: 'entrance',
            geometry: entranceResult.features[0].geometry,
            attributes: entranceResult.features[0].attributes,
          }
          facilityInfoVisible.value = true
          return
        }
      }

      // 查询服务区图层
      if (serviceLayer && serviceLayer.visible) {
        const serviceResult = await serviceLayer.queryFeatures(query)
        if (serviceResult.features.length > 0) {
          // 找到服务区，显示信息
          selectedFacility = {
            type: 'service',
            geometry: serviceResult.features[0].geometry,
            attributes: serviceResult.features[0].attributes,
          }
          facilityInfoVisible.value = true
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })

  // 加载高速公路列表
  loadHighwayList()
  // 加载服务区和进出口列表
  loadServiceList()
  loadEntranceList()
}

// 组件挂载时初始化地图
onMounted(() => {
  nextTick(() => {
    initMap()
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 10;
}

.layer-card {
  width: 280px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

/* 图层说明提示样式 */
.layer-info-tip {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 12px;
  z-index: 100;
  max-width: 200px;
  font-size: 12px;
}

.tip-title {
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
  border-bottom: 1px solid #ddd;
  padding-bottom: 4px;
}

.tip-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.color-box {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  display: inline-block;
}

/* 高速公路状态颜色 */
.highway-good {
  background-color: #67C23A;
}

.highway-normal {
  background-color: #E6A23C;
}

.highway-bad {
  background-color: #F56C6C;
}

.highway-repair {
  background-color: #EE1414;
}

/* 点图层颜色 */
.entrance {
  background-color: #3498DB;
}

.service {
  background-color: #27AE60;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #409eff;
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.collapse-title {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.collapse-title .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.route-info-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 10;
  max-width: 400px;
  max-height: 500px;
  overflow-y: auto;
}

.route-card {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.route-title {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.route-title .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.route-details {
  font-size: 14px;
  padding: 8px 0;
}

.route-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.route-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #409eff;
}

.route-steps {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.steps-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 15px;
}

.steps-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.steps-list {
  margin: 0;
  padding-left: 24px;
}

.steps-list li {
  margin-bottom: 8px;
  line-height: 1.5;
  padding: 6px 0;
  border-bottom: 1px dashed #dcdfe6;
}

.steps-list li:last-child {
  border-bottom: none;
}

.facility-item {
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  background-color: #f5f7fa;
  transition: background-color 0.3s;
}

.facility-item:hover {
  background-color: #ecf5ff;
}

.query-section {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.section-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
  font-size: 14px;
}

.note-text {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.dialog-footer .el-button {
  margin-left: 12px;
}

/* 添加响应式设计 */
@media screen and (max-width: 768px) {
  .layer-card {
    width: 240px;
  }

  .route-info-panel {
    max-width: 300px;
  }
}
</style>
